package bll

import (
	"context"
	"fmt"
	"gitlab.local/backend/pkg/cron"
	log "simcard/collector/logger"
	"simcard/errors"
	"simcard/model"
	"strings"
	"sync"
	"time"
)

var (
	SimCardCron = &simCardCron{
		Cron: cron.New(cron.WithLocation(time.Local), cron.WithSeconds()),
	}
)

type simCardCron struct {
	*cron.Cron
	initFinished bool
}

func (a *simCardCron) initLoadData() error {

	var (
		initCount = 2
		wp        = sync.WaitGroup{}
		logMsg    []string
	)

	wp.Add(initCount)
	//go func() {
	//	opt := &model.SimCardBaseInfoCronRequest{
	//		DataMode: model.SimCardSyncDataPartOf,
	//		Ebikes:   []int64{22},
	//	}
	//	err := a.syncCardBaseInfo(nil,opt)
	//	logMsg = append(logMsg, fmt.Sprintf("%+v", err))
	//	wp.Done()
	//}()

	//go func() {
	//	defer wp.Done()
	//	return
	//	opt := &model.SimCardConsumptionInfoCronRequest{
	//		DataMode: model.SimCardSyncDataPartOf,
	//		Ebikes:   []int64{22},
	//	}
	//	err := a.syncCardConsumptionInfo(nil,opt)
	//
	//	logMsg = append(logMsg, fmt.Sprintf("%+v", err))
	//
	//}()

	go func() {
		req := &model.SimCardUpdateExpiringRequest{
			DataRange: model.SimCardSyncDataAll,
		}
		err := a.updateExpiringStatus(nil, req)
		logMsg = append(logMsg, fmt.Sprintf("%+v", err))
		wp.Done()
	}()

	go func() {
		req := &model.UpdateActiveRequest{
			DataRange: model.SimCardSyncDataAll,
		}
		err := a.updateActiveStatus(nil, req)
		logMsg = append(logMsg, fmt.Sprintf("%+v", err))
		wp.Done()
	}()

	wp.Wait()
	a.initFinished = true
	return errors.New(strings.Join(logMsg, ","))
}

func (a *simCardCron) init() func() {

	a.Start()

	var (
		scheduleJobList = []struct {
			Spec    string
			Comment string
			Desc    string
			cron.FuncJob
		}{
			//{
			//	//Spec: "@every 30s",
			//	Spec: "@every 12h",
			//	//Spec:    "@weekly",
			//	Comment: "每周检查一次",
			//	Desc:    "同步卡自身信息(手机号,ICCID,SN,FRAME_CODE),不包括流量/状态信息",
			//	FuncJob: a.SyncCardBaseInfo,
			//},

			{
				//Spec: "@every 30s",
				Spec: "@monthly",
				//Spec:    "@weekly",
				Comment: "每月检查一次",
				Desc:    "检查预付费的表，是否有记录触发流量卡充值",
				FuncJob: a.SyncCardConsumptionInfo,
			},
			{
				//Spec: "@every 30s",
				Spec: "@every 30m",
				//Spec:    "@weekly",
				Comment: "每30分钟检查一次",
				Desc:    "",
				FuncJob: a.UpdateExpiringStatus,
			},
			{
				//Spec: "@every 30s",
				Spec: "@monthly",
				//Spec:    "@weekly",
				Comment: "每月检查一次有没有激活的设备",
				Desc:    "",
				FuncJob: a.UpdateActiveStatus,
			},
		}
	)

	for _, v := range scheduleJobList {
		_, _ = a.AddFunc(v.Spec, v.FuncJob)
	}

	go func() {
		log.Info(fmt.Sprintf("%+v", a.initLoadData()))
	}()

	return func() {}
}

//func (a *simCardCron) SyncCardBaseInfo(args ...interface{}) {
//
//	for !a.initFinished {
//		time.Sleep(1 * time.Second)
//	}
//	log.Info(fmt.Sprintf("%+v", a.syncCardBaseInfo(args...)))
//}

//func (a *simCardCron) syncCardBaseInfo(args ...interface{}) error {
//
//	/* Full synchronization */
//
//	return nil
//	arg := &model.SimCardBaseInfoCronRequest{}
//	//arg := &model.SimCardBaseInfoCronRequest{
//	//	Ebikes: []int64{13286},
//	//}
//	if len(args) > 0 {
//		arg = args[0].(*model.SimCardBaseInfoCronRequest)
//	}
//
//	return SimCard.SyncCardBaseInfo(context.Background(), arg)
//}

func (a *simCardCron) SyncCardConsumptionInfo(args ...interface{}) {

	for !a.initFinished {
		time.Sleep(1 * time.Second)
	}
	req := &model.SimCardUpdateExpiringRequest{
		DataRange: model.SimCardSyncDataAll,
	}
	log.Info(fmt.Sprintf("%+v", a.syncCardConsumptionInfo(nil,req)))
}

func (a *simCardCron) syncCardConsumptionInfo(args ...interface{}) error {

	arg := &model.SimCardConsumptionInfoCronRequest{}
	if len(args) > 1 {
		arg = args[1].(*model.SimCardConsumptionInfoCronRequest)
	}

	return SimCard.SyncCardConsumptionInfo(context.Background(), arg)
}

func (a *simCardCron) UpdateExpiringStatus(args ...interface{}) {

	for !a.initFinished {
		time.Sleep(1 * time.Second)
	}

	req := &model.SimCardUpdateExpiringRequest{
		DataRange: model.SimCardSyncDataAll,
	}
	log.Info(fmt.Sprintf("%+v", a.updateExpiringStatus(nil,req)))
}

func (a *simCardCron) updateExpiringStatus(args ...interface{}) error {

	ctx, _ := context.WithTimeout(context.Background(), time.Minute*3)
	opt := &model.SimCardUpdateExpiringRequest{}
	if len(args) > 1 {
		opt = args[1].(*model.SimCardUpdateExpiringRequest)
	}
	return SimCard.UpdateExpiringStatus(ctx, opt)
}

func (a *simCardCron) UpdateActiveStatus(args ...interface{}) {

	for !a.initFinished {
		time.Sleep(1 * time.Second)
	}

	req := &model.UpdateActiveRequest{
		DataRange: model.SimCardSyncDataAll,
	}
	log.Info(fmt.Sprintf("%+v", a.updateActiveStatus(nil,req)))
}

func (a *simCardCron) updateActiveStatus(args ...interface{}) error {

	ctx, _ := context.WithTimeout(context.Background(), time.Minute*3)
	opt := &model.UpdateActiveRequest{}
	if len(args) > 1 {
		opt = args[1].(*model.UpdateActiveRequest)
	}
	return SimCard.UpdateActiveStatus(ctx, opt)
}
